package com.pangu.util.rules.model;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.model.PlayerRecordHonghei;
import com.pangu.core.engine.game.model.Summary;
import com.pangu.core.engine.game.model.SummaryPlayer;
import com.pangu.util.ProcessCard;
import com.pangu.util.UKTools;
import com.pangu.util.disruptor.DisruptorHandler;
import com.pangu.web.model.GamePlayway;
import com.pangu.web.model.GameRoom;
import com.pangu.web.model.PlayUserClient;
import com.pangu.web.service.impl.BroadcastServiceImpl;
import com.pangu.web.service.repository.es.PlayUserClientESRepository;
import com.pangu.web.service.repository.es.PlayerRecordHongheiESRepository;
import com.pangu.web.service.repository.jpa.PlayUserClientRepository;
import com.pangu.web.service.repository.jpa.PlayerRecordHongheiRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RedBlackBoard extends Board implements java.io.Serializable {

	/**
	 * Description:
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public Summary summary(Board board, GameRoom gameRoom, GamePlayway playway) {
		Summary summary = new Summary(gameRoom.getId(), board.getId(), board.getRatio(),
				board.getRatio() * playway.getScore());

		List<PlayUserClient> plays = CacheHelper.getGamePlayerCacheBean().getCacheObject(gameRoom.getId(),
				gameRoom.getOrgi());
		NiuniuPosition[] p = board.getNiuniuPosition();

		Map<String, Object> map = ProcessCard.whoIsWinner(board);// 红胜还是黑胜
		int whoWin = Integer.parseInt(map.get("flag").toString());
		board.setWinner(whoWin + "");// 加入谁赢了
		int cardType = 99;
		// 根据赢家进行赋值花色
		if (whoWin == 1) {
			cardType = Integer.parseInt(map.get("redCardType").toString());
		} else if (whoWin == 2) {
			cardType = Integer.parseInt(map.get("blackCardType").toString());
		}
		double tem = 0.00;
		double temSum;// 当局输赢总量
		SummaryPlayer summaryPlayer = null;
		PlayUserClient playUserClient = null;
		// 根据下注记录进行结算。
		for (int i = 0; i < plays.size(); i++) {
			temSum = 0.00;
			playUserClient = plays.get(i);
			// 如果不是ai就重新获取一下对象
			if (!playUserClient.getPlayertype().equals(BMDataContext.BEIMI_GAME_AI)) {
				playUserClient = (PlayUserClient) CacheHelper.getApiUserCacheBean()
						.getCacheObject(playUserClient.getId(), gameRoom.getOrgi());
			}
			// 获取此用户的下注记录
			List<PlayerRecordHonghei> prList = (List<PlayerRecordHonghei>) CacheHelper.getGameRecordHongheiCacheBean()
					.getCacheObject(playUserClient.getId(), playUserClient.getOrgi());
			// 若没有下注，则不管
			if (prList == null || prList.size() < 1) {
				// log.info("没有下注，无法结算");
				continue;
			}
			for (PlayerRecordHonghei pr : prList) {
				if (playUserClient.getGoldcoins() < pr.getCoin()) {
					// log.info("下注记录超过本金，无法结算");
					continue;
				}
				// 下注金额
				double betCount = pr.getCoin();
				// 下注类型，红胜1，黑胜2，幸运3
				int seat = Integer.parseInt(pr.getGameSubType());// playUserClient.getSeat();//
				// 押对了
				if (seat == whoWin) {
					// 赢钱
					// 余额和下注金额相加
					tem = betCount * board.getRatio();
				} else {
					// 看是否是押的幸运
					if (seat == 3) {
						// int cardType = 99;
						int ratio = -1;// 幸运的赔率
						// 根据花色进行赋值赔率
						if (cardType == 6) {//
							ratio = 10;
						} else if (cardType == 5) {// 顺金
							ratio = 5;
						} else if (cardType == 4) {// 金花
							ratio = 3;
						} else if (cardType == 3) {// 顺子
							ratio = 2;
						} else if (cardType == 2) {// 对子
							ratio = 1;
						}
						tem = betCount * ratio;
					} else {
						// 输钱
						tem = betCount * board.getRatio() * -1;
					}
				}
				log.info("=======================" + playUserClient.getUsername() + "下注后结果是：" + tem);
				// 记录日志
				// PlayerRecord pr = new PlayerRecord();
				// pr.setRoomId(gameRoom.getId());// 房间id
				pr.setOrgi(gameRoom.getOrgi());
				// 本局牌型，用|隔开，第一组是红，第二组是黑，第三组是红的牌型，第四组是黑的牌型，第五组为谁胜，后三是黑，格式为：1,2,3|4,5,6|6|2|1
				String c = ProcessCard.byteRedBlackCardToString(p[0].getCards(), p[1].getCards()) + "|"
						+ map.get("redCardType") + "|" + map.get("blackCardType") + "|" + whoWin;
				pr.setCards(c);
				pr.setGameType(BMDataContext.GameTypeEnum.HONGHEI.toString());
				pr.setWinLoseCoin(tem);// 输赢金额
				// pr.setSummaryId(UKTools.getUUID());// 暂时写一个，没跟结算有联系
				pr.setGameId(board.getId());
				// pr.setPlayerType(playUserClient.getPlayertype());
				DisruptorHandler.published(pr,
						BMDataContext.getContext().getBean(PlayerRecordHongheiESRepository.class),
						BMDataContext.getContext().getBean(PlayerRecordHongheiRepository.class));

				playUserClient.setGoldcoins(playUserClient.getGoldcoins() + (new Double(tem)).intValue());
				CacheHelper.getGamePlayerCacheBean().put(playUserClient.getId(), playUserClient, gameRoom.getOrgi());
				// 持久化用户数据
				DisruptorHandler.published(playUserClient,
						BMDataContext.getContext().getBean(PlayUserClientESRepository.class),
						BMDataContext.getContext().getBean(PlayUserClientRepository.class));
				// 封装结算对象，返回给前端
				summaryPlayer = new SummaryPlayer(playUserClient.getId(), playUserClient.getUsername(), 0, 0,
						tem > 0 ? true : false, false);
				summaryPlayer.setScore(tem);// 输赢金额
				summaryPlayer.setBalance(playUserClient.getGoldcoins());
				summary.getPlayers().add(summaryPlayer);
				temSum += tem;
			}
			// 当赢得本局金额总量大于此金额的时候保存在广播表，并进行广播
			if (BMDataContext.BEIMI_BROADCAST_VALUE < temSum) {
				BroadcastServiceImpl broadcastServiceImpl = BMDataContext.getContext()
						.getBean(BroadcastServiceImpl.class);
				broadcastServiceImpl.saveAndSendSocketBroadcast(playUserClient, temSum,
						BMDataContext.GameTypeEnum.HONGHEI.toString());
			}
			// 如果真人客户已经离开房间变成托管玩家，那么结算完就删除游戏房间的相关信息
			if (playUserClient.getPlayertype().equals(BMDataContext.PlayerTypeEnum.OFFLINE.toString())) {
				CacheHelper.getGamePlayerCacheBean().delete(playUserClient.getId(), playUserClient.getOrgi());
				CacheHelper.getRoomMappingCacheBean().delete(playUserClient.getId(), playUserClient.getOrgi());
			}
			// log.info(gameRoom.getId() + "========" + playUserClient.getPlayertype());
			// 结算完成就删除
			CacheHelper.getGameRecordHongheiCacheBean().delete(playUserClient.getId(), playUserClient.getOrgi());
		}
		// 存入牌局信息
		GameHistoryBoard gameHistoryBoard = new GameHistoryBoard(board.getId(), board.getWinner(), cardType + "",
				new Date(), gameRoom.getId());
		CacheHelper.getGameHistoryBoardCache().put(gameHistoryBoard.getId(), gameHistoryBoard, gameRoom.getOrgi());
		
		board.setFinished(true);
		CacheHelper.getBoardCacheBean().put(board.getRoom(), board, gameRoom.getOrgi());
		return summary;
	}

	@Override
	public byte[] pollLastHands() {
		return null;
	}

	@Override
	public int calcRatio() {
		return 0;
	}

	@Override
	public TakeCards takeCards(Player player, String playerType, TakeCards current) {
		return null;
	}

	@Override
	public int index(String userid) {
		return 0;
	}

	@Override
	public boolean isWin() {
		return false;
	}

	@Override
	protected Player next(int index) {
		return null;
	}

	@Override
	public Player nextPlayer(int index) {
		return null;
	}

	@Override
	public TakeCards takecard(Player player, boolean allow, byte[] playCards) {
		return null;
	}

	@Override
	public TakeCards takecard(Player player) {
		return null;
	}

	@Override
	public TakeCards takeCardsRequest(GameRoom gameRoom, Board board, Player player, String orgi, boolean auto,
			byte[] playCards) {
		return null;
	}

	@Override
	public void dealRequest(GameRoom gameRoom, Board board, String orgi, boolean reverse, String nextplayer) {

	}

	@Override
	public void playcards(Board board, GameRoom gameRoom, Player player, String orgi) {

	}

	@Override
	public TakeCards takecard(Player player, TakeCards last) {
		return null;
	}

}
